package com.gwt.cloud.result;


import com.gwt.cloud.constant.ApiResultEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.io.Serializable;

@Data
public class ApiResult<T> implements Serializable {

    @ApiModelProperty("状态代码")
    private Integer status;

    @ApiModelProperty("消息描述")
    private String message;

    @ApiModelProperty("是否成功")
    private Boolean success;

    @ApiModelProperty("返回数据")
    private T data;

    private ApiResult(T data, Integer status, String message){
        this.data = data;
        this.message = message;
        this.status = status;
        if (getSuccess()){
            if (!StringUtils.hasText(message)){
                this.message = ApiResultEnum.SUCCESS.getMessage();
            }
        }
    }

    public ApiResult(T data) {
        this(data, ApiResultEnum.SUCCESS.getStatus(), ApiResultEnum.SUCCESS.getMessage());
    }

    public ApiResult(T data, String msg) {
        this(data, ApiResultEnum.SUCCESS.getStatus(), msg);
    }

    public ApiResult(Integer status, String msg) {
        this(null, status, msg);
    }

    public ApiResult() {
        this(null, null, null);
    }

    public static <T> ApiResult<T> ok(){
        return new ApiResult<>(ApiResultEnum.SUCCESS.getStatus(), ApiResultEnum.SUCCESS.getMessage());
    }
    public static <T> ApiResult<T> ok(T data){
        return new ApiResult<>(data);
    }

    /**
     * 运行错误
     * @param message 错误消息
     * @return ApiResult
     * @param <T> <T>
     */
    public static <T> ApiResult<T> error(String message){
        return new ApiResult<>(ApiResultEnum.FAIL.getStatus(), message);
    }

    /**
     * 授权已过期
     * @return ApiResult
     * @param <T> <T>
     */
    public static <T> ApiResult<T> expire(){
        return new ApiResult<>(ApiResultEnum.LOGIN_EXPIRE.getStatus(), ApiResultEnum.LOGIN_EXPIRE.getMessage());
    }

    /**
     * 权限不足拒绝访问
     * @return ApiResult
     * @param <T> <T>
     */
    public static <T> ApiResult<T> refuse(){
        return new ApiResult<>(ApiResultEnum.ACCESS_REFUSE.getStatus(), ApiResultEnum.ACCESS_REFUSE.getMessage());
    }
    public Boolean getSuccess() {
        return ApiResultEnum.SUCCESS.getStatus().equals(status);
    }
}
